import threading

from django.core.mail import send_mail
from django.conf import settings


class EmailSender(threading.Thread):
    def __init__(self, cache_val, request, *args, **kwargs):
        self.cache_val = cache_val
        self.request = request
        super().__init__(*args, **kwargs)

    def run(self) -> None:
        # 如果间隔大于60秒则发送
        send_mail(subject='您的账号的验证码',
                  message=f'您的验证码是（有效期为10分钟）：{self.cache_val.get("captcha")}',
                  from_email=settings.EMAIL_HOST_USER,
                  recipient_list=[self.cache_val.get('email')],
                  fail_silently=False)


def send_captcha_email(cache_val, request):
    sender = EmailSender(cache_val=cache_val, request=request)
    sender.start()
